package com.goods.business.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goods.business.mapper.*;
import com.goods.business.service.InStockService;
import com.goods.business.service.SupplierService;
import com.goods.common.enums.buisiness.StatusEnum;
import com.goods.common.model.business.*;
import com.goods.common.response.ActiveUser;
import com.goods.common.vo.business.InStockDetailVO;
import com.goods.common.vo.business.InStockItemVO;
import com.goods.common.vo.business.InStockVO;
import com.goods.common.vo.business.SupplierVO;
import com.goods.common.vo.system.UserInfoVO;
import io.swagger.models.auth.In;
import org.apache.poi.hpsf.Variant;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description：
 * @version:
 * @author：ruixinag
 * @create：Created in 2021/11/9 4:01
 */
@Service
public class InStockServiceImpl implements InStockService {
    @Autowired
    private InStockMapper inStockMapper;
    @Autowired
    private SupplierService supplierService;

    //入库单（入库记录）数据分页列表展示
    @Override
    public Map findInStockList(Map paramMap) {
        String pageNum = (String) paramMap.get("pageNum");
        String pageSize = (String) paramMap.get("pageSize");
        String status = (String) paramMap.get("status");
        String type = (String) paramMap.get("type");
        String inNum = (String) paramMap.get("inNum");

        String startTime = (String) paramMap.get("startTime");
        String endTime = (String) paramMap.get("endTime");


        Example example = new Example(InStock.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("status", status);
        if (!StringUtils.isEmpty(type)) {
            criteria.andEqualTo("type", type);
        }

        if (!StringUtils.isEmpty(inNum)) {
            criteria.andLike("inNum", "%" + inNum + "%");
        }
        if (!StringUtils.isEmpty(startTime)) {
            criteria.andGreaterThan("createTime", startTime);
        }
        if (!StringUtils.isEmpty(endTime)) {
            criteria.andLessThan("createTime", endTime);
        }


        //分页插件
        PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        List<InStock> inStocks = inStockMapper.selectByExample(example);
        PageInfo<InStock> pageInfo = new PageInfo<>(inStocks);

        List<InStockVO> inStockVOS = pageInfo.getList().stream().map(inStock -> {
            InStockVO inStockVO = new InStockVO();
            BeanUtils.copyProperties(inStock, inStockVO);

            //获取提供方信息,如果有的话
            if (null != inStock.getSupplierId() && !StringUtils.isEmpty(inStock.getSupplierId())) {
                SupplierVO supplierVO = supplierService.edit(inStock.getSupplierId());
                inStockVO.setSupplierName(supplierVO.getName());
                inStockVO.setPhone(supplierVO.getPhone());
                inStockVO.setAddress(supplierVO.getAddress());
                inStockVO.setEmail(supplierVO.getEmail());
                inStockVO.setContact(supplierVO.getContact());
            }

            return inStockVO;
        }).collect(Collectors.toList());



        Map result = new HashMap<>();
        result.put("rows", inStockVOS);
        result.put("total", pageInfo.getTotal());
        return result;
    }

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private InStockInfoMapper inStockInfoMapper;
    @Autowired
    private SupplierMapper supplierMapper;
    @Autowired
    private ProductStockMapper productStockMapper;

    //查入库明细
    @Override
    public InStockDetailVO detail(Long inStockId, int pageNum) {

        //1.查出入库单的信息
        InStock inStock = inStockMapper.selectByPrimaryKey(inStockId);
        //2.然后再从product表中获取具体的物资信息
        InStockDetailVO inStockDetailVO = new InStockDetailVO();
        BeanUtils.copyProperties(inStock, inStockDetailVO);

        //3.根据instock的in_num,在in_stock_info中查出与之相关的信息,
        Example o1 = new Example(InStockInfo.class);
        o1.createCriteria().andEqualTo("inNum", inStockDetailVO.getInNum());
        //分页展示,默认为3条信息, 前端需要的为3
        PageHelper.startPage(pageNum, 3);
        List<InStockInfo> inStockInfoList = inStockInfoMapper.selectByExample(o1);
        PageInfo<InStockInfo> pageInfo = new PageInfo<>(inStockInfoList);

        List<InStockItemVO> list = inStockInfoList.stream().map(inStockInfo -> {
            InStockItemVO inStockItemVO = new InStockItemVO();
            //设置数量
            inStockItemVO.setCount(inStockInfo.getProductNumber());
            //根据p_num查商品信息
            Example o2 = new Example(Product.class);
            o2.createCriteria().andEqualTo("pNum", inStockInfo.getPNum());
            Product product = productMapper.selectOneByExample(o2);
            BeanUtils.copyProperties(product, inStockItemVO);
            return inStockItemVO;
        }).collect(Collectors.toList());

        inStockDetailVO.setItemVOS(list);

        //设置总数
        inStockDetailVO.setTotal(pageInfo.getTotal());

        //根据supplier_id,查供应商信息
        Supplier supplier = supplierMapper.selectByPrimaryKey(inStock.getSupplierId());
        SupplierVO supplierVO = new SupplierVO();
        BeanUtils.copyProperties(supplier, supplierVO);
        inStockDetailVO.setSupplierVO(supplierVO);
        return inStockDetailVO;
    }

    //放入回收站
    @Override
    public void remove(Long inStockId) {
        changeStatus(inStockId, StatusEnum.RECYCLE.getCode());
    }

    //还原
    @Override
    public void back(Long inStockId) {
        changeStatus(inStockId, StatusEnum.NORMAL.getCode());
    }

    //新增入库单
    @Override
    public void addIntoStock(InStockVO inStockVO) {
        InStock inStock = new InStock();
        //1.先判断来源是新增还是已有的
        if (!StringUtils.isEmpty(inStockVO.getSupplierId()) && null != inStockVO.getSupplierId()) {
            //1.1.已有供应商
            inStock.setSupplierId(inStockVO.getSupplierId());
        } else {
            //1.2 新增供应商
            Supplier supplier = new Supplier();
            BeanUtils.copyProperties(inStockVO, supplier);
            supplier.setCreateTime(new Date());
            supplier.setModifiedTime(new Date());
            supplierMapper.insertSelective(supplier);
            inStock.setSupplierId(supplier.getId());
        }
        //组装入库单需要的数据
        inStock.setType(inStockVO.getType());
        inStock.setRemark(inStockVO.getRemark());
        //获取当前用户信息
        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
        inStock.setOperator(activeUser.getUser().getUsername());

        //时间
        inStock.setCreateTime(new Date());
        inStock.setModified(new Date());
        //商品数量
        inStock.setProductNumber(inStockVO.getProducts().size());

        //入库单序号
        String uuid = UUID.randomUUID().toString();
        String inNum = uuid.replace("-", "");
        inStock.setInNum(inNum);
        //新增入库单表
        inStockMapper.insertSelective(inStock);

        //新增in_stock_info
        //根据inStockVO.products信息表,其中的数据结构为List<Map>,遍历此list,,新增
        List<Object> products = inStockVO.getProducts();
        products.stream().forEach(product -> {
            Map<String, Integer> map = (Map) product;
            InStockInfo inStockInfo = new InStockInfo();
            inStockInfo.setInNum(inStock.getInNum());
            inStockInfo.setCreateTime(new Date());
            inStockInfo.setModifiedTime(new Date());
            inStockInfo.setProductNumber(map.get("productNumber"));
            Product product1 = productMapper.selectByPrimaryKey(map.get("productId"));
            inStockInfo.setPNum(product1.getPNum());
            inStockInfoMapper.insertSelective(inStockInfo);


        });


    }

    //审核通过
    @Override
    public void publish(Long inStockId) {
        //1.更改状态
        InStock inStock = inStockMapper.selectByPrimaryKey(inStockId);
        inStock.setStatus(StatusEnum.NORMAL.getCode());
        inStockMapper.updateByPrimaryKey(inStock);
        //2.增加库存
        //2.1 根据inNum查instockInfo,
        Example example = new Example(InStockInfo.class);
        example.createCriteria().andEqualTo("inNum", inStock.getInNum());
        List<InStockInfo> inStockInfoList = inStockInfoMapper.selectByExample(example);
        inStockInfoList.stream().forEach(inStockInfo -> {
            //根据pNum,到productStock查询,
            //对应的商品增加库存
            //现根据pNum查,查不到则新增
            Example o = new Example(ProductStock.class);
            o.createCriteria().andEqualTo("pNum", inStockInfo.getPNum());
            ProductStock productStock = productStockMapper.selectOneByExample(o);
            if (null != productStock) {
                //追加库存
                productStock.setStock(productStock.getStock() + inStockInfo.getProductNumber());
                productStockMapper.updateByPrimaryKey(productStock);
            } else {
                //新增商品库存
                productStock = new ProductStock();
                productStock.setPNum(inStockInfo.getPNum());
                productStock.setStock(Long.parseLong(inStockInfo.getProductNumber().toString()));
                productStockMapper.insertSelective(productStock);
            }

        });

    }

    //删除入库单,相关联的in_stock_info的数据也删除
    @Override
    public void delete(Long inStockId) {
        //1.删除入库单,instock
        InStock inStock = inStockMapper.selectByPrimaryKey(inStockId);
        inStockMapper.deleteByPrimaryKey(inStockId);
        //2.删除入库详细表,instockInfo
        Example o = new Example(InStockInfo.class);
        o.createCriteria().andEqualTo("inNum", inStock.getInNum());
        inStockInfoMapper.deleteByExample(o);
    }

    //更改入库单状态
    private void changeStatus(Long inStockId, int status) {
        InStock inStock = inStockMapper.selectByPrimaryKey(inStockId);
        inStock.setStatus(status);
        inStockMapper.updateByPrimaryKey(inStock);
    }
}
